<?php
declare(strict_types=1);

namespace App\Service\Web;

use App\Enum\Code;
use App\Exception\BusinessException;
use App\Mail\WelcomeMailWithText;
use App\Repository\Web\UserFollowsRepository;
use App\Repository\Web\UserRepository;
use App\Repository\Web\UserProfilesRepository;
use Hyperf\Context\Context;
use HyperfExt\Jwt\Contracts\JwtFactoryInterface;
use HyperfExt\Jwt\Contracts\ManagerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Di\Annotation\Inject;

class UserFollowsService
{

    protected RequestInterface $request;

    public function __construct(RequestInterface $request)
    {
        $this->request = $request;
    }

    #[Inject]
    private UserFollowsRepository $userFollowsRepository;
    #[Inject]
    protected UserRepository $userRepository;
    #[Inject]
    protected UserProfilesRepository $userProfilesRepository;

    public function up_down($data)
    {
        $followingId = $data['following_id'];
        $followerId = Context::get('uid');

        $following = $this->userRepository->find($followingId);
        if (empty($following)) {
            throw new BusinessException(Code::ResourceNotFound, '被关注用户不存在');
        }
        $exist = $this->userFollowsRepository->findOneBy([
            'follower_id' => $followerId,
            'following_id' => $followingId,
        ]);
        if ($exist) {
            // 取消关注
            $this->userFollowsRepository->delete($exist->id);
            return ['type' => 'cancel', 'following_id' => $followingId];
        } else {
            // 关注
            $this->userFollowsRepository->create(
                [
                    'follower_id' => $followerId,
                    'following_id' => $followingId,
                ]
            );
            return ['type' => 'add', 'following_id' => $followingId];
        }
    }

    public function follows()
    {
        $perPage = $this->request->query('per_page', 30);
        $page = $this->request->query('page', 1);
        $userId = Context::get('uid');
        return $this->userFollowsRepository
            ->findWithFollows($userId,$perPage,$page);
    }
    public function following()
    {
        $perPage = $this->request->query('per_page', 30);
        $page = $this->request->query('page', 1);
        $userId = Context::get('uid');
        return $this->userFollowsRepository
            ->findWithFollows($userId,$perPage,$page);
    }
}